package com.hunantv.mglive.ui.live;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import mgtvcom.devsmart.android.ui.HorizontalListView;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BaseActivity;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.Constant;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.data.LiveDetailModel;
import com.hunantv.mglive.data.LiveUrlModel;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.StarModel;
import com.hunantv.mglive.data.VODModel;
import com.hunantv.mglive.data.live.ChatData;
import com.hunantv.mglive.ui.adapter.LiveCameraAdapter;
import com.hunantv.mglive.utils.L;
import com.hunantv.mglive.utils.ReportUtil;
import com.hunantv.mglive.utils.SharePreferenceUtils;
import com.hunantv.mglive.utils.ShareUtil;
import com.hunantv.mglive.utils.StringUtil;
import com.hunantv.mglive.utils.Toast;
import com.hunantv.mglive.widget.GiftViewAnim;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.hunantv.mglive.R.drawable.live;

public class LiveDetailActivity extends BaseActivity implements ChatViewCallback, View.OnClickListener, Animation.AnimationListener, LiveDetailVideoFragment.IVideoViewCallBcak, AdapterView.OnItemClickListener, StarLiveDetailCentreFragment.ICenterViewCallback {
    public static final String JUMP_INTENT_TITLE = "JUMP_INTENT_TITLE";
    public static final String JUMP_INTENT_SHOW_COUNT = "JUMP_INTENT_SHOW_COUNT";

    private String mLid;
    private String mType;
    private String mShowCount = "1";

    private int mWidth;
    private int mHeight;
    private int mCountTime;
    private boolean mIsAnim;
    private boolean mIsCameraShowing;
    private boolean mIsCamera;
    private boolean mIsLand;
    private boolean mAutoRotateOn;

    private View mVChat;
    private TextView mTvTitle;
    private RelativeLayout mRvTitle;
    private TitleViewHolder mTitleHolder;

    private HorizontalListView mHorizontalListView;

    private ShareUtil mShare;
    private GiftViewAnim mGiftViewAnim;
    private LiveDetailModel mDetailModel;
    private LiveDetailModel mCheckedDetailModel;
    //视频卡顿上报类型，直播，点播
    private String upPlayVedioType;

    private StarModel mCheckedStar;
    private LiveCameraAdapter mAdapter;
    private ChatFragment mChatFragment;
    private GiftFragment mGiftFragment;
    private LiveDetailVideoFragment mVideoFragment;
    private List<LiveDetailModel> mList = new ArrayList<>();

    private TranslateAnimation mAnimationUpToDown;
    private TranslateAnimation mAnimationUpToDownBack;
    private Handler mHandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            mCountTime++;
            if (mCountTime >= 5) {
                if (mHorizontalListView.getVisibility() == View.VISIBLE) {
                    hideCameraView();
                }
            } else {
                mHandler.sendEmptyMessageDelayed(0, 1000);
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewGroup mViewGroup = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.activity_live_detail, null);
        setContentView(mViewGroup);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        Intent intent = getIntent();
        if (intent != null) {
            mLid = intent.getStringExtra(Constant.JUMP_INTENT_LID);
            mType = intent.getStringExtra(Constant.JUMP_INTENT_TYPE);
            mShowCount = intent.getStringExtra(JUMP_INTENT_SHOW_COUNT);
        }
        if (StringUtil.isNullorEmpty(mLid)) {
            finish();
            return;
        }

        mVideoFragment = (LiveDetailVideoFragment) getSupportFragmentManager().findFragmentById(R.id.fragmenrt_live_video);
        mChatFragment = (ChatFragment) getSupportFragmentManager().findFragmentById(R.id.fragmenrt_live_chat);
        mChatFragment.setChatViewCallback(this);
        mChatFragment.setVideoViewListener(this);
        mVideoFragment.setVideoViewCallBack(this);

        initView();
        initAnim();

        mShare = new ShareUtil(this);
        mGiftViewAnim = new GiftViewAnim(this, mViewGroup);
        Map<String, String> requestBody = new FormEncodingBuilderEx().add(Constant.KEY_LID, mLid).add(Constant.KEY_TYPE, mType).build();
        post(BuildConfig.URL_GET_DETAIL, requestBody);
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            changeToLandView();
        }
    }

    private void initView() {
        mVChat = findViewById(R.id.ll_live_detail_chat);
        setLayoutParams(mIsLand);

        mRvTitle = (RelativeLayout) findViewById(R.id.rl_live_star_title);

        mTitleHolder = new TitleViewHolder();
        ImageButton ibtnBack = (ImageButton) findViewById(R.id.ibtn_live_detail_back);
        ibtnBack.setOnClickListener(this);
        mTitleHolder.btn1 = (ImageButton) findViewById(R.id.ibtn_live_detail_1);
        mTitleHolder.line1 = findViewById(R.id.v_live_detail_line1);
        mTitleHolder.btn2 = (ImageButton) findViewById(R.id.ibtn_live_detail_2);
        mTitleHolder.line2 = findViewById(R.id.v_live_detail_line2);
        mTitleHolder.btn3 = (ImageButton) findViewById(R.id.ibtn_live_detail_3);

        SharePreferenceUtils sharePreferenceUtils = new SharePreferenceUtils(this, SharePreferenceUtils.FILE_KEY_HINT_DATA);
        boolean isCameraDisPlay = sharePreferenceUtils.isCamreHintDisplay();
        if (isCameraDisPlay) {
            mTitleHolder.btn3.setImageResource(R.drawable.camera_point);
        }

        mTitleHolder.btn1.setOnClickListener(this);
        mTitleHolder.btn2.setOnClickListener(this);
        mTitleHolder.btn3.setOnClickListener(this);
        mTvTitle = (TextView) findViewById(R.id.tv_live_full_title);

        mHorizontalListView = (HorizontalListView) findViewById(R.id.hlv_live_detail_cameras);
        mHorizontalListView.setOnItemClickListener(this);
        mHorizontalListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    mHandler.removeMessages(0);
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    mHandler.sendEmptyMessageDelayed(0, 1000);
                }
                return false;
            }
        });

        setGifView();
    }

    private void initAnim() {
        mAnimationUpToDown = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0);
        mAnimationUpToDown.setDuration(300);
        mAnimationUpToDownBack = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1);
        mAnimationUpToDownBack.setDuration(300);
        mAnimationUpToDown.setAnimationListener(this);
        mAnimationUpToDownBack.setAnimationListener(this);
    }

    public void setGifView() {
        mGiftFragment = (GiftFragment) getSupportFragmentManager().findFragmentById(R.id.fragmenrt_gift);
        mGiftFragment.setGiftAnimListener(this);
    }

    private void setLayoutParams(boolean island) {
        View v = findViewById(R.id.ll_live_detail_vido);
        RelativeLayout.LayoutParams ps = (RelativeLayout.LayoutParams) v.getLayoutParams();
        if (!island) {
            //按比例缩放直播窗体
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int width = dm.widthPixels > dm.heightPixels ? dm.heightPixels : dm.widthPixels;
            mWidth = width;
            mHeight = (int) (width * 0.75);
            ps.height = mHeight;//0.56
        } else {
            ps.height = RelativeLayout.LayoutParams.MATCH_PARENT;
            ps.width = RelativeLayout.LayoutParams.MATCH_PARENT;
        }
        v.setLayoutParams(ps);
    }

    private void getVideoUri(String type, String video) {
        if (LiveDetailModel.TYPE_LIVE.equals(type)) {
            Map<String, String> requestBody = new FormEncodingBuilderEx()
                    .add(Constant.KEY_CHANNELID, video)
                    .add(Constant.KEY_RATE, Constant.DE_RATE)
                    .add(Constant.KEY_USER_ID, getUid()).build();
            L.d(TAG, mDetailModel.getVideo());
            post(BuildConfig.URL_GET_LIVE_PLAY_URL, requestBody);
        } else {
            Map<String, String> requestBody = new FormEncodingBuilderEx()
                    .add(Constant.KEY_MEDIAID, video)
                    .add(Constant.KEY_RATE, Constant.DE_RATE)
                    .add(Constant.KEY_TYPE, "mid")
                    .add(Constant.KEY_USER_ID, getUid()).build();
            L.d(TAG, mDetailModel.getVideo());
            post(BuildConfig.URL_GET_VIDEO_URL, requestBody);
        }
    }


    private void setDetailModel(LiveDetailModel liveDetailModel, String videoPath) {
        if (liveDetailModel == null) {
            return;
        }
        liveDetailModel.setShowCount(mShowCount);
        mVideoFragment.setDetailModel(liveDetailModel, videoPath, mIsCamera);

        List<StarModel> user = liveDetailModel.getUsers();
        if (user.size() > 0) {
            mChatFragment.setStarList(user);
            mChatFragment.setStarInfo(user.get(0));
        }

        if (!StringUtil.isNullorEmpty(liveDetailModel.getChatFlag())) {
            mChatFragment.setData(liveDetailModel.getChatFlag(), liveDetailModel.getChatKey());
        } else {
            if (LiveDetailModel.TYPE_LIVE.equals(liveDetailModel.getType())) {
                liveDetailModel.setChatFlag(ChatFragment.TYPE_LIVE);
                liveDetailModel.setChatKey(liveDetailModel.getlId() + "/" + liveDetailModel.getVideo());
                mChatFragment.setData(ChatFragment.TYPE_LIVE, liveDetailModel.getlId() + "/" + liveDetailModel.getVideo());
            } else if (LiveDetailModel.TYPE_BACK.equals(liveDetailModel.getType())) {
                liveDetailModel.setChatFlag(ChatFragment.TYPE_BACK);
                liveDetailModel.setChatKey(liveDetailModel.getlId());
                mChatFragment.setData(ChatFragment.TYPE_BACK, liveDetailModel.getlId());
            }
        }

    }

    private void setTitle(String title) {
        if (mTvTitle != null && !StringUtil.isNullorEmpty(title)) {
            mTvTitle.setText(title);
        }
    }

    private void changeTitleTab() {
        if (mTvTitle == null) {
            return;
        }
        if (mIsLand) {
            mTvTitle.setVisibility(View.VISIBLE);
            mTitleHolder.btn1.setSelected(true);
            mTitleHolder.btn1.setImageResource(R.drawable.danmu_bg);
        } else {
            mTvTitle.setVisibility(View.GONE);
            mTitleHolder.btn1.setImageResource(R.drawable.vedio_full);
        }
    }

    @Override
    public void finish() {
        getMqtt().stopMQTTService();
        super.finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (mGiftFragment.onBackpressed()) {
                return true;
            }
            if (mChatFragment != null && mChatFragment.onBackPressed()) {
                return true;
            }
            backPressed();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onError(String url, Exception e) {
        if (e != null && !StringUtil.isNullorEmpty(e.getMessage())) {
            Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        super.onError(url, e);
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        super.onFailure(url, resultModel);
        if(!StringUtil.isNullorEmpty(mVodRequestUrl) && mVodRequestUrl.equals(url))
        {
            try {
                JSONObject jsonData = new JSONObject(resultModel.getData());
                playVod(jsonData.getString("info"));

                //把code转成2开头
                String responseCode = resultModel.getResponseCode();
                if(!StringUtil.isNullorEmpty(responseCode)){
                    String subFirst = responseCode.substring(0,1);
                    responseCode = responseCode.replace(subFirst,"2");
                }
                String param = StringUtil.urlJoint(mVodRequestUrl, resultModel.getParam());
                ReportUtil.instance().report(mVodRequestUrl, param, "0", "2", responseCode, false);

                mVodRequestUrl = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) throws JSONException {
        super.onSucceed(url, resultModel);
        if (url.contains(BuildConfig.URL_GET_DETAIL)) {
            mDetailModel = (LiveDetailModel) resultModel.getDataModel();
            if (mDetailModel != null) {
                mChatFragment.setTitle(mDetailModel.getTitle());
                setTitle(mDetailModel.getTitle());
                getVideoUri(mDetailModel.getType(), mDetailModel.getVideo());
                if (mDetailModel.getRelationLives() != null && mDetailModel.getRelationLives().size() > 1) {
                    mTitleHolder.btn3.setVisibility(View.VISIBLE);
                    mTitleHolder.line2.setVisibility(View.VISIBLE);
                    mIsCamera = true;
                    for (LiveDetailModel liveDetailModel : mDetailModel.getRelationLives()) {
                        if (liveDetailModel.getlId().equals(mDetailModel.getlId())) {
                            mCheckedDetailModel = liveDetailModel;
                            break;
                        }
                    }
                } else {
                    mIsCamera = false;
                }
                mList.addAll(mDetailModel.getRelationLives());
                mAdapter = new LiveCameraAdapter(this, mList);
                mAdapter.setCheckedLive(mCheckedDetailModel);
                mHorizontalListView.setAdapter(mAdapter);
            }
            if (mCheckedDetailModel == null) {
                mCheckedDetailModel = mDetailModel;
            }
//            setDetailModel(mCheckedDetailModel, null);// TODO: 2016/5/19 先注释,会导致连接两次聊天室
        } else if (BuildConfig.URL_GET_LIVE_PLAY_URL.equals(url)) {
            String mVideoPath = resultModel.getDataModel().toString();
            setDetailModel(mCheckedDetailModel, mVideoPath);
        }else if (url.contains(BuildConfig.URL_GET_VIDEO_URL)) {
            VODModel vod = (VODModel) resultModel.getDataModel();
            if(vod != null){
                if(vod.isMgtvType()){
                    getVodUrl(vod.getPlayUrl());
                }else {
                    playVod(vod.getPlayUrl());
                }
            }
        }else if(!StringUtil.isNullorEmpty(mVodRequestUrl) && mVodRequestUrl.equals(url))
        {
            try {
                JSONObject jsonData = new JSONObject(resultModel.getData());
                playVod(jsonData.getString("info"));

                String param = StringUtil.urlJoint(mVodRequestUrl, resultModel.getParam());
                ReportUtil.instance().report(mVodRequestUrl, param, "0", "2", "", true);

                mVodRequestUrl = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        if (BuildConfig.URL_GET_VIDEO_URL.contains(url)) {
            return JSON.parseObject(resultModel.getData(),VODModel.class);
        } else if (BuildConfig.URL_GET_LIVE_PLAY_URL.contains(url)) {
            List<LiveUrlModel> list = JSON.parseArray(resultModel.getData(), LiveUrlModel.class);
            return StringUtil.getPlayUrl(list);
        }
        return JSON.parseObject(resultModel.getData(), LiveDetailModel.class);
    }

    //点播类型为MGTV时缓存请求URl
    private String mVodRequestUrl;

    private void getVodUrl(String url){
        mVodRequestUrl = url;
        if(!StringUtil.isNullorEmpty(mVodRequestUrl)){
            get(url,null);
        }
    }

    private void playVod(String url){
        setDetailModel(mCheckedDetailModel, url);
    }

    @Override
    public void startAnim(String image, String text, int fromx, int fromy) {
        mGiftViewAnim.startGiftViewAnim(image, text, fromx, mWidth / 2, fromy, mHeight / 2);
    }

    @Override
    public void hasMsg(ChatData chatData) {
        if (chatData.getType() == ChatData.CHAT_TYPE_STAR_CHANGE) {
            if (!mCheckedDetailModel.getlId().equals(chatData.getRoomId())) {
                for (LiveDetailModel mode : mDetailModel.getRelationLives()) {
                    if (chatData.getShowOwners() != null && !chatData.getShowOwners().isEmpty()) {
                        String uid = chatData.getShowOwners().get(0).getUid();
                        List<StarModel> users = mode.getUsers();
                        for (StarModel model : users) {
                            if (model.getUid().equals(uid)) {
                                users.remove(model);
                                users.add(0, model);
                                return;
                            }
                        }
                    }
                }
            }
        }
        if (mVideoFragment != null) {
            mVideoFragment.doMsg(chatData);
        }
    }

    @Override
    public void changeOnline(String changeStr) {
        if (mVideoFragment != null) {
            mVideoFragment.changeOnline(changeStr);
        }
    }

    @Override
    public void changeGiftView(boolean isDisplay) {
        if (mGiftFragment != null) {
            if (isDisplay) {
                mGiftFragment.showGiftView();
            } else {
                mGiftFragment.hideGiftView();
            }
        }
    }

    @Override
    public void changeStarHotValue(long hotValue) {
        if (mVideoFragment != null) {
            mVideoFragment.changeStarHotValue(hotValue);
        }
    }

    @Override
    public void onClick(View v) {
            if(v.getId() == R.id.ibtn_live_detail_back){
                backPressed();
            }else if(v.getId() == R.id.ibtn_live_detail_1){
                if (mVideoFragment != null) {
                    mVideoFragment.setCountTime(0);
                }
                if (!mIsLand) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    if (mAutoRotateOn) {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                            }
                        }, 3000);
                    }
                } else {
                    if (mVideoFragment != null) {
                        mVideoFragment.changeDanmu(v);
                    }
                }
            }else if(v.getId() == R.id.ibtn_live_detail_2){
                if (mVideoFragment != null) {
                    mVideoFragment.setCountTime(0);
                }
                if (mDetailModel != null) {
                    if (mIsLand) {
                        mShare.shareAsFull(getUid(), getToken(), ShareUtil.TYPE_LIVE_ROOM, mDetailModel.getlId(), "", "", mDetailModel.getType());
                    } else {
                        mShare.share(getUid(), getToken(), ShareUtil.TYPE_LIVE_ROOM, mDetailModel.getlId(), "", "", mDetailModel.getType());
                    }
                }
            }else if(v.getId() == R.id.ibtn_live_detail_3){
                SharePreferenceUtils sharePreferenceUtils = new SharePreferenceUtils(this, SharePreferenceUtils.FILE_KEY_HINT_DATA);
                sharePreferenceUtils.setCamreHintDisplay(false);
                mTitleHolder.btn3.setImageResource(R.drawable.camera);
                if (mVideoFragment != null) {
                    mVideoFragment.setCountTime(0);
                }
                showCameraView();
            }
    }

    private void backPressed() {
        if (mIsLand) {
            if (mVideoFragment != null) {
                mVideoFragment.setCountTime(0);
            }
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                }
            }, 3000);
        } else {
            finish();
        }
    }

    @Override
    public boolean changeTitle(boolean changeDisplay, boolean isClick) {
        if (mHorizontalListView.getVisibility() == View.VISIBLE && isClick) {
            mHandler.removeMessages(0);
            hideCameraView();
            return false;
        }
        if (changeDisplay) {
            mRvTitle.startAnimation(mAnimationUpToDown);
        } else {
            mRvTitle.startAnimation(mAnimationUpToDownBack);
        }
        return true;
    }

    @Override
    public void changeStar(StarModel model) {
        mCheckedStar = model;
        if (mChatFragment != null) {
            mChatFragment.setStarInfo(model);
        }
        if (mGiftFragment != null) {
            mGiftFragment.setStarInfo(model);
        }
    }

    @Override
    public void showGift() {
        if (mGiftFragment != null) {
            mGiftFragment.showGiftView();
        }
    }

    @Override
    public void onAnimationStart(Animation animation) {

    }

    @Override
    public void onAnimationEnd(Animation animation) {
        if (animation == mAnimationUpToDownBack) {
            mRvTitle.setVisibility(View.GONE);
        } else if (animation == mAnimationUpToDown) {
            mRvTitle.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Adapter adapter = parent.getAdapter();
        mCheckedDetailModel = (LiveDetailModel) adapter.getItem(position);
        mAdapter.setCheckedLive(mCheckedDetailModel);
        mAdapter.notifyDataSetChanged();
        mHandler.removeMessages(0);
        mCountTime = 0;
        mHandler.sendEmptyMessageDelayed(0, 1000);
        Toast.makeText(this, getString(R.string.live_start_change, mCheckedDetailModel.getTitle()), Toast.LENGTH_SHORT).show();
        if (mCheckedDetailModel != null) {
            setTitle(mCheckedDetailModel.getTitle());
            getVideoUri(mCheckedDetailModel.getType(), mCheckedDetailModel.getVideo());
        }
        hideCameraView();
    }

    public synchronized void showCameraView() {
        if (mIsAnim || mIsCameraShowing) {
            return;
        }
        mIsAnim = true;
        TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0);
        translateAnimation.setDuration(300);
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mIsAnim = false;
                mIsCameraShowing = true;
                mHorizontalListView.setVisibility(View.VISIBLE);
                mAdapter.notifyDataSetChanged();
                mHandler.removeMessages(0);
                mCountTime = 0;
                mHandler.sendEmptyMessageDelayed(0, 1000);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mHorizontalListView.startAnimation(translateAnimation);
    }


    public synchronized void hideCameraView() {
        if (mIsAnim || !mIsCameraShowing) {
            return;
        }
        mIsAnim = true;
        TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1);
        translateAnimation.setDuration(300);
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mIsAnim = false;
                mIsCameraShowing = false;
                mHorizontalListView.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mHorizontalListView.startAnimation(translateAnimation);
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            changeToLandView();
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            changeToPortraitView();
        }
    }

    private void changeToPortraitView() {
        mShare.dismiss();
        hideCameraView();
        if (mGiftFragment != null) {
            mGiftFragment.hideGiftView();
            mGiftFragment.onScreenChange(false);
        }
        mIsLand = false;
//        mVChat.setVisibility(View.VISIBLE);
        setLayoutParams(false);
        if (mVideoFragment != null) {
            mVideoFragment.screenOrietantionChanged(false);
        }
        if (mChatFragment != null) {
            mChatFragment.screenOrietantionChanged(false);
        }
        changeTitleTab();
    }

    private void changeToLandView() {
        mShare.dismiss();
        hideCameraView();
        if (mGiftFragment != null) {
            mGiftFragment.hideGiftView();
            mGiftFragment.onScreenChange(true);
        }
        mIsLand = true;
        setLayoutParams(true);
        if (mVideoFragment != null) {
            mVideoFragment.screenOrietantionChanged(true);
        }
        if (mChatFragment != null) {
            mChatFragment.screenOrietantionChanged(true);
        }
//        mVChat.setVisibility(View.GONE);
        changeTitleTab();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void pauseVideo() {
        if (mVideoFragment != null) {
            mVideoFragment.pauseVideo();
            Log.i(TAG,"pauseVideo");
        }
    }

    @Override
    public void starVideo() {
        if (mVideoFragment != null) {
            mVideoFragment.starVideo();
            Log.i(TAG, "startVideo");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mAutoRotateOn = (android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1);
    }

    class TitleViewHolder {
        ImageButton btn1;
        View line1;
        ImageButton btn2;
        View line2;
        ImageButton btn3;
    }
}
